package com.ruoyi.am.controller;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.am.domain.*;
import com.ruoyi.am.utils.JsonUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.am.service.IAmMapsService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.client.RestTemplate;

/**
 * 急救车调度Controller
 * 
 * @author hkkk
 * @date 2021-05-17
 */
@Controller
@RequestMapping("/am/maps")
public class AmMapsController extends BaseController
{
    private String prefix = "am/maps";
    private final String AK_BROWSER = "34wG1jfGGOZ0ZWrS9jga0XY7mkBOGAb6";
    private final String AL_SERVER = "sbknoUqD7WM5tdlj63BPlGOnbikgxglD";

    private static List<AmCarLocation> locations = new ArrayList<>();
    private static List<AmCarLocation> waitAss = new ArrayList<>();

    @Autowired
    private IAmMapsService amMapsService;

    @RequiresPermissions("am:maps:view")
    @GetMapping()
    public String maps()
    {
        UnitTest();
        return prefix + "/maps";
    }

    /**
     * 查询急救车调度列表
     */
    @RequiresPermissions("am:maps:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AmMaps amMaps)
    {
        startPage();
        List<AmMaps> list = amMapsService.selectAmMapsList(amMaps);
        return getDataTable(list);
    }

    /**
     * 导出急救车调度列表
     */
    @RequiresPermissions("am:maps:export")
    @Log(title = "急救车调度", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AmMaps amMaps)
    {
        List<AmMaps> list = amMapsService.selectAmMapsList(amMaps);
        ExcelUtil<AmMaps> util = new ExcelUtil<AmMaps>(AmMaps.class);
        return util.exportExcel(list, "maps");
    }

    /**
     * 新增急救车调度
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存急救车调度
     */
    @RequiresPermissions("am:maps:add")
    @Log(title = "急救车调度", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AmMaps amMaps)
    {
        return toAjax(amMapsService.insertAmMaps(amMaps));
    }

    /**
     * 修改急救车调度
     */
    @GetMapping("/edit/{mapId}")
    public String edit(@PathVariable("mapId") Long mapId, ModelMap mmap)
    {
        AmMaps amMaps = amMapsService.selectAmMapsById(mapId);
        mmap.put("amMaps", amMaps);
        return prefix + "/edit";
    }

    /**
     * 修改保存急救车调度
     */
    @RequiresPermissions("am:maps:edit")
    @Log(title = "急救车调度", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AmMaps amMaps)
    {
        return toAjax(amMapsService.updateAmMaps(amMaps));
    }

    /**
     * 删除急救车调度
     */
    @RequiresPermissions("am:maps:remove")
    @Log(title = "急救车调度", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(amMapsService.deleteAmMapsByIds(ids));
    }


    public AmDes getDistance(double origin_lat, double origin_lng, double destinations_lat, double destinations_lng){
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://api.map.baidu.com/routematrix/v2/driving?output=json&origins="
                + origin_lat + "," + origin_lng + "&destinations=" +destinations_lat +"," +destinations_lng
                + "&ak=" + AL_SERVER;
        String res = restTemplate.getForObject(url, String.class);
        AmDes amDes = JsonUtil.getDes(res);
        return amDes;
    }

    public void getRecentCar(double lat, double lng){
        List<AmDes> desList = new ArrayList<>();

        for(AmCarLocation amCarLocation:locations){
            AmDes amDes = getDistance(amCarLocation.getLat(), amCarLocation.getLng(), lat, lng);
            if(!amCarLocation.isIs_busy()) {
                amDes.setCar_num(amCarLocation.getCar_num());
                amDes.setDriver_id(amCarLocation.getDriver_id());
                desList.add(amDes);
            }
        }

        desList.sort((x, y)->Double.compare(x.getDuration().getValue(), y.getDuration().getValue()));

        for(AmCarLocation amCarLocation:locations){
            if (desList.get(0).getCar_num().equals(amCarLocation.getCar_num())){
                waitAss.add(amCarLocation);
                return;
            }
        }

    }

    public AmAssistance queryTask(String carNum){
        for (AmCarLocation amCarLocation:waitAss){
            if(amCarLocation.getCar_num().equals(carNum)){
                AmAssistance amAssistance = new AmAssistance();
                amAssistance.setCar_num(amCarLocation.getCar_num());
                amAssistance.setDriver_id(amCarLocation.getDriver_id());
                amAssistance.setPhone("120");
                amAssistance.setDoctor("doctor");
                amAssistance.setNourse("nourse");
                amAssistance.setLat(amCarLocation.getLat());
                amAssistance.setLng(amCarLocation.getLng());
                amAssistance.setLocation("苍梧区");
                return amAssistance;
            }
        }
        return null;
    }

    public void UnitTest(){
        try {
            AmCarLocation location =new AmCarLocation("10065", "苏G2576", 40.45, 116.34, false);
            AmCarLocation location1 =new AmCarLocation("10066", "苏G1486", 40.25, 116.74, false);
            AmCarLocation location2 =new AmCarLocation("10067", "苏G4476", 40.55, 116.39, false);
            updateLocation(location);
            updateLocation(location1);
            updateLocation(location2);

            getRecentCar(40.55,116.40);
            AmAssistance a1 = queryTask("苏G2576");
            AmAssistance a2 = queryTask("苏G1486");
            AmAssistance a3 = queryTask("苏G4476");
            return;
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    @PostMapping("/update_location")
    public void updateLocation(AmCarLocation location){
        if(locations == null){
            locations = new ArrayList<>();
        }

        if (!locations.contains(location)){
            locations.add(location);
        }
        else {
            for (AmCarLocation amCarLocation:locations){
                if (location.equals(amCarLocation)){
                    amCarLocation.setLat(location.getLat());
                    amCarLocation.setLng(location.getLng());
                }
            }
        }
    }

}
